﻿using Furion.DatabaseAccessor;
using Furion.DependencyInjection;
using Furion.DynamicApiController;
using Furion.FriendlyException;
using iWare.Wms.Core;
using iWare.Wms.Core.Entity.Warehouse.view;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Linq.Dynamic.Core;

namespace iWare.Wms.Application
{
    /// <summary>
    /// 物料服务
    /// </summary>
    [Route("api/WareMaterial")]
    [ApiDescriptionSettings("仓库基础数据", Name = "Material", Order = 100)]

    public class WareMaterialService : ControllerBase, IDynamicApiController, ITransient
    {
        private readonly IRepository<WareMaterial, MasterDbContextLocator> _wareMaterialRep; //物料仓储
        private readonly IRepository<WareMaterialWarehouse, MasterDbContextLocator> _wareMaterialWarehouseRep; //品号仓库仓储
        private readonly IRepository<v_material_warehouse, MasterDbContextLocator> _vMaterialWarehouseRep; //物料与品号仓库试图仓储

        #region 默认
        /// <summary>
        /// 默认
        /// </summary>
        /// <param name="wareMaterialRep"></param>
        /// <param name="wareMaterialWarehouseRep"></param>
        /// <param name="vMaterialWarehouseRep"></param>
        public WareMaterialService(
            IRepository<WareMaterial, MasterDbContextLocator> wareMaterialRep,
            IRepository<WareMaterialWarehouse, MasterDbContextLocator> wareMaterialWarehouseRep,
            IRepository<v_material_warehouse, MasterDbContextLocator> vMaterialWarehouseRep
        )
        {
            _wareMaterialRep = wareMaterialRep;
            _wareMaterialWarehouseRep = wareMaterialWarehouseRep;
            _vMaterialWarehouseRep = vMaterialWarehouseRep;
        }
        #endregion

        /// <summary>
        /// 分页查询物料
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpGet("page")]
        public async Task<PageResult<WareMaterialOutput>> Page([FromQuery] WareMaterialSearch input)
        {
            var wareMaterials = await _vMaterialWarehouseRep.DetachedEntities
                .Where(!string.IsNullOrEmpty(input.Code), u => EF.Functions.Like(u.Code, $"%{input.Code.Trim()}%"))
                .Where(!string.IsNullOrEmpty(input.Name), u => EF.Functions.Like(u.Name, $"%{input.Name.Trim()}%"))
                .Where(input.InspectionMethod != InspectionMethodEnum.all, u => u.InspectionMethod == input.InspectionMethod)
                .Where(input.SecurityStatus == YesOrNot.N, u => u.InventoryQuantity <= u.SafetyQuantity)
                .Where(!string.IsNullOrEmpty(input.SearchBeginTime), u => u.CreatedTime >= DateTime.Parse(input.SearchBeginTime.Trim()) &&
                 u.CreatedTime <= DateTime.Parse(input.SearchEndTime.Trim()))
                //.OrderBy(PageInputOrder.OrderBuilder<WareMaterialSearch>(input))
                .OrderByDescending(z => z.SafetyQuantity)
                .ProjectToType<WareMaterialOutput>()
                .ToADPagedListAsync(input.PageNo, input.PageSize);

            foreach (var item in wareMaterials.Rows)
            {
                item.BrandName = string.IsNullOrEmpty(item.BrandName) || item.BrandName == "无" ? "" : item.BrandName;
            }

            return wareMaterials;
        }

        /// <summary>
        /// 新增物料表
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("add")]
        public async Task Add([FromBody] AddWareMaterialInput input)
        {
            var isExist = await _wareMaterialRep.DetachedEntities.AnyAsync(u => u.Code == input.Code);
            if (isExist) throw Oops.Oh("数据已存在");

            var wareMaterial = input.Adapt<WareMaterial>();
            await _wareMaterialRep.InsertAsync(wareMaterial);
        }

        /// <summary>
        /// 删除物料表
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("delete")]
        public async Task Delete([FromBody] DeleteWareMaterialInput input)
        {
            int length = input.Id.Count;
            for (int i = 0; i < length; i++)
            {
                long Id = input.Id[i];
                var wareMaterial = await _wareMaterialRep.FirstOrDefaultAsync(u => u.Id == Id);
                await _wareMaterialRep.DeleteAsync(wareMaterial);
            }
        }

        /// <summary>
        /// 更新物料表
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("edit")]
        public async Task Update([FromBody] UpdateWareMaterialInput input)
        {
            var isExist = await _wareMaterialRep.AnyAsync(u => u.Id == input.Id, false);
            if (!isExist) throw Oops.Oh("数据不存在");

            var wareMaterial = input.Adapt<WareMaterial>();
            await _wareMaterialRep.UpdateAsync(wareMaterial, ignoreNullValues: true);
        }
    }
}
